home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 4: GNU Archives / Linux Cubed Series 4 - GNU Archives.iso / gnu / termutil.0 / termutil / termutils-2.0 / bsearch.c next >
Encoding:
C/C++ Source or Header  |  1995-09-02  |  1.5 KB  |  55 lines

  1. /* Copyright (C) 1991, 1992 Free Software Foundation, Inc.
  2.  
  3.    This program is free software; you can redistribute it and/or modify
  4.    it under the terms of the GNU General Public License as published by
  5.    the Free Software Foundation; either version 2, or (at your option)
  6.    any later version.
  7.  
  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.
  12.  
  13.    You should have received a copy of the GNU General Public License
  14.    along with this program; if not, write to the Free Software
  15.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  16.  
  17. #ifdef STDC_HEADERS
  18. #include <stdlib.h>
  19. #else
  20. #define NULL 0
  21. #include <sys/types.h>
  22. #endif
  23.  
  24. /* Perform a binary search for KEY in BASE which has NMEMB elements
  25.    of SIZE bytes each.  The comparisons are done by (*COMPAR)().  */
  26. char *
  27. bsearch (key, base, nmemb, size, compar)
  28.      register char *key;
  29.      register char *base;
  30.      size_t nmemb;
  31.      register size_t size;
  32.      register int (*compar) ();
  33. {
  34.   register size_t l, u, idx;
  35.   register char *p;
  36.   register int comparison;
  37.  
  38.   l = 0;
  39.   u = nmemb;
  40.   while (l < u)
  41.     {
  42.       idx = (l + u) / 2;
  43.       p = (char *) (((char *) base) + (idx * size));
  44.       comparison = (*compar) (key, p);
  45.       if (comparison < 0)
  46.     u = idx;
  47.       else if (comparison > 0)
  48.     l = idx + 1;
  49.       else
  50.     return (char *) p;
  51.     }
  52.  
  53.   return NULL;
  54. }
  55.